using Services;
using System;
using System.Diagnostics;
using UnityEngine;
using WebSocketSharp;

public class ClientManager : Service,IService
{
    public Action<string> AfterRecieveMessage;
    public override Type RegisterType => GetType();

    [AutoService]
    private GameManager gameManager;
    [SerializeField]
    private string address;
    private WebSocket socket;

    public bool connected;

    public void Send(string input)
    {
        socket?.Send(input);
    }

    public void Connect()
    {
        if(socket == null || !socket.IsAlive)
        {
            socket = new WebSocket(address);
            socket.Connect();
            socket.OnMessage += OnMessage;
        }
        Ping();
    }

    public void Ping()
    {
        if (socket != null && socket.IsAlive)
            connected = true;
    }

    private void AfterGameStateChange(bool _)
        => Ping();

    protected internal override void Init()
    {
        base.Init();
        Connect();
        gameManager = ServiceLocator.Get<GameManager>();
        gameManager.AfterGameStateChange += AfterGameStateChange;
    }

    private void OnMessage(object sender, MessageEventArgs args)
    {
        AfterRecieveMessage?.Invoke(args.Data);
    }

    private void OnDestroy()
    {
        gameManager.AfterGameStateChange -= AfterGameStateChange;
        socket?.Close();
        Process[] processes = Process.GetProcessesByName("gobang_ai_server");
        for (int i = 0; i < processes.Length; i++)
        {
            processes[i].Close();
        }
    }
}
